<template>
  <div>
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>非药品收费项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>非药品收费项目列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 功能按钮 -->
    <el-row :gutter="20">
      <el-col :span="3" :offset="6">
        <el-button type="primary" icon="el-icon-circle-plus" @click="itemDialogVisible = true">新增项目</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="danger" icon="el-icon-delete-solid" @click="removeBatch(sels)">批量删除</el-button>
      </el-col>
      <el-col :span="3">
        <el-upload
          class="filter-item"
          name="excelFile"
          :action="uploadUrl()"
          :on-error="uploadFalse"
          :on-success="uploadSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          accept=".xlsx, .xls"
          :show-file-list="false"
          :file-list="fileList"
          ref="upload"
        >
          <el-button style="margin-left: 10px;" icon="el-icon-edit" type="primary">导入项目</el-button>
        </el-upload>
      </el-col>
      <el-col :span="3">
        <el-button @click="downloadDemo" type="info" icon="el-icon-download">下载模板</el-button>
      </el-col>
    </el-row>

    <!-- 条件搜索栏 -->
    <el-form
      ref="searchFormRef"
      :model="queryForm"
      label-width="40px"
      label-position="top"
      :inline="true"
      class="demo-form-inline"
    >
      <el-form-item label="项目编码">
        <el-input placeholder="请填写项目编码" v-model="queryForm.itemcode" clearable></el-input>
      </el-form-item>
      <el-form-item label="项目名称">
        <el-input placeholder="请填写项目名称" v-model="queryForm.itemname" clearable></el-input>
      </el-form-item>
      <el-form-item label="费用分类">
        <el-select v-model="queryForm.expclassid">
          <el-option label="空" value></el-option>
          <el-option v-for="item in options1" :key="item.id" :label="item.expname" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="执行科室">
        <el-select v-model="queryForm.deptid">
          <el-option label="空" value></el-option>
          <el-option
            v-for="item in options2"
            :key="item.id"
            :label="item.deptname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-top:50px;margin-left:20px">
        <el-button type="success" @click="queryFmeditem">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- card展示 -->
    <el-card>
      <el-table @selection-change="selsChange" :data="fmeditemList" border stripe>
        <!-- 为表格添加一个编号（索引） -->
        <el-table-column type="selection" width="65"></el-table-column>
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column prop="itemcode" label="项目编码" width="100"></el-table-column>
        <el-table-column prop="itemname" label="项目名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="format" label="规格"></el-table-column>
        <el-table-column prop="price" label="单价"></el-table-column>
        <el-table-column prop="expenseclass.expname" label="所属费用科目" width="100"></el-table-column>
        <el-table-column prop="department.deptname" label="执行科室"></el-table-column>
        <el-table-column prop="mnemoniccode" label="拼音助记码" width="90" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creationdate" label="创建时间" :formatter="formatDate1" width="100"></el-table-column>
        <el-table-column prop="lastupdatedate" label="最后修改时间" width="100" :formatter="formatDate2"></el-table-column>
        <el-table-column prop="recordtype" label="项目类型" :formatter="formatType"></el-table-column>
        <el-table-column width="200px" label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除信息" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeFmedById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- Pagination分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加信息弹出框 -->
    <el-dialog title="添加项目" :visible.sync="itemDialogVisible" width="50%">
      <!-- 创建一个添加项目表单 -->
      <!-- 写完表单后要添加数据绑定以及检验的规则 -->
      <el-form :model="itemForm" :rules="femdFormRules" ref="itemFormRef">
        <el-form-item prop="itemcode" label="项目编码">
          <el-input
            v-model="itemForm.itemcode"
            prefix-icon="iconfont icon-user"
            placeholder="请填写项目编码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="itemname" label="项目名称">
          <el-input
            v-model="itemForm.itemname"
            prefix-icon="iconfont icon-user"
            placeholder="请填写项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="format" label="规格">
          <el-input v-model="itemForm.format" prefix-icon="iconfont icon-user" placeholder="请填写规格"></el-input>
        </el-form-item>
        <el-form-item prop="mnemoniccode" label="拼音助记码">
          <el-input
            v-model="itemForm.mnemoniccode"
            prefix-icon="iconfont icon-user"
            placeholder="请填写拼音助记码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="price" label="单价">
          <el-input v-model="itemForm.price" prefix-icon="iconfont icon-user" placeholder="请填写单价"></el-input>
        </el-form-item>
        <el-form-item prop="expclassid" label="费用分类">
          <el-select v-model="itemForm.expclassid" placeholder="请选择费用分类">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.expname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deptid" label="科室类型">
          <el-select v-model="itemForm.deptid" placeholder="请选择科室类型">
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.deptname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="recordtype" label="项目类型">
          <el-select v-model="itemForm.recordtype" placeholder="请选择科室类型">
            <el-option
              v-for="item in options3"
              :key="item.recordtype"
              :label="item.label"
              :value="item.recordtype"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="itemDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹出框 -->
    <el-dialog title="修改用户" :visible.sync="updateDialogVisible" width="50%">
      <!-- 创建一个表单 -->
      <!-- 写完表单后要修改数据绑定以及检验的规则 -->
      <el-form :model="updateForm" :rules="femdFormRules" ref="updateFormRef">
        <el-form-item prop="itemcode" label="项目编码">
          <el-input
            v-model="updateForm.itemcode"
            prefix-icon="iconfont icon-user"
            placeholder="请填写项目编码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="itemname" label="项目名称">
          <el-input
            v-model="updateForm.itemname"
            prefix-icon="iconfont icon-user"
            placeholder="请填写项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="format" label="规格">
          <el-input
            v-model="updateForm.format"
            prefix-icon="iconfont icon-user"
            placeholder="请填写规格"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mnemoniccode" label="拼音助记码">
          <el-input
            v-model="updateForm.mnemoniccode"
            prefix-icon="iconfont icon-user"
            placeholder="请填写拼音助记码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="price" label="单价">
          <el-input v-model="updateForm.price" prefix-icon="iconfont icon-user" placeholder="请填写单价"></el-input>
        </el-form-item>
        <el-form-item prop="expclassid" label="费用分类">
          <el-select v-model="updateForm.expclassid" placeholder="请选择费用分类">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.expname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deptid" label="科室类型">
          <el-select v-model="updateForm.deptid" placeholder="请选择科室类型">
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.deptname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="recordtype" label="项目类型">
          <el-select v-model="updateForm.recordtype" placeholder="请选择科室类型">
            <el-option
              v-for="item in options3"
              :key="item.recordtype"
              :label="item.label"
              :value="item.recordtype"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="sureUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //列表显示条目总数
      total: 0,
      sels: [],
      //费用分类选择器
      options1: [],
      //执行科室类型选择器
      options2: [],
      //项目分类选择器
      options3: [
        {
          recordtype: 1,
          label: "检查",
        },
        {
          recordtype: 2,
          label: "检验",
        },
        {
          recordtype: 3,
          label: "处置",
        },
      ],
      //项目列表信息
      fmeditemList: [],
      //添加信息表单
      itemForm: {
        itemcode: "",
        itemname: "",
        format: "",
        mnemoniccode: "",
        price: null,
        expclassid: null,
        deptid: null,
        recordtype: null,
      },
      //修改表单信息
      updateForm: {
        id: "",
        itemcode: "",
        itemname: "",
        format: "",
        mnemoniccode: "",
        price: null,
        expclassid: null,
        deptid: null,
        recordtype: null,
      },
      //初始化分页信息
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      //查询表单信息
      queryForm: {
        itemcode: "",
        itemname: "",
        expclassid: "",
        deptid: "",
        pageNum: "1",
        pageSize: "5",
      },
      //添加Dilog框默认为关闭
      itemDialogVisible: false,
      //修改查询Dilog框默认关闭
      updateDialogVisible: false,
      fileList: [],
      femdFormRules: {
        itemcode: [
          { required: true, message: "项目编码不能为空", trigger: "blur" },
        ],
        itemname: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        format: [
          { required: true, message: "规格不能为空", trigger: "blur" },
        ],
        mnemoniccode: [
          { required: true, message: "拼音助记码不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" },
        ],
        expclassid: [
          {
            required: true,
            message: "所属费用科目不能为空",
            trigger: ["blur", "change"],
          },
        ],
        deptid: [
          {
            required: true,
            message: "执行科室不能为空",
            trigger: ["blur", "change"],
          },
        ],
        recordtype: [
          {
            required: true,
            message: "项目类型不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      
    };
  },
  created() {
    //初始化列表查询
    this.getFmeditemList(),
      //初始费用分类选择器
      this.getExpItem();
    //初始化执行科室分类选择器
    this.getDeptItem();
  },
  methods: {
    //创建时间字段格式化
    formatDate1(row, column) {
      let date = new Date(parseInt(row.creationdate));
      let Y = date.getFullYear() + "-";
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1) + "-"
          : date.getMonth() + 1 + "-";
      let D =
        date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
      let h =
        date.getHours() < 10
          ? "0" + date.getHours() + ":"
          : date.getHours() + ":";
      let m =
        date.getMinutes() < 10
          ? "0" + date.getMinutes() + ":"
          : date.getMinutes() + ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    //最后修改时间字段格式化
    formatDate2(row, column) {
      if (row.lastupdatedate == null) {
        return "";
      } else {
        let date = new Date(parseInt(row.lastupdatedate));
        let Y = date.getFullYear() + "-";
        let M =
          date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1) + "-"
            : date.getMonth() + 1 + "-";
        let D =
          date.getDate() < 10
            ? "0" + date.getDate() + " "
            : date.getDate() + " ";
        let h =
          date.getHours() < 10
            ? "0" + date.getHours() + ":"
            : date.getHours() + ":";
        let m =
          date.getMinutes() < 10
            ? "0" + date.getMinutes() + ":"
            : date.getMinutes() + ":";
        let s =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return Y + M + D + h + m + s;
      }
    },
    //项目类型字段格式化
    formatType: function (row, column) {
      if (row.recordtype == "1") {
        return "检查";
      } else if (row.recordtype == "2") {
        return "检验";
      } else {
        return "处置";
      }
    },
    //分页按钮功能
    handleSizeChange(size) {
      if (
        this.queryForm.itemname != "" ||
        this.queryForm.itemcode != "" ||
        this.queryForm.expclassid != "" ||
        this.queryForm.deptid != ""
      ) {
        this.queryForm.pageSize = String(size);
        this.queryFmeditem();
      } else {
        this.queryInfo.pageSize = size;
        //重新查询科室信息
        this.getFmeditemList();
      }
    },
    handleCurrentChange(page) {
      if (
        this.queryForm.itemname != "" ||
        this.queryForm.itemcode != "" ||
        this.queryForm.expclassid != "" ||
        this.queryForm.deptid != ""
      ) {
        this.queryForm.pageNum = String(page);
        this.queryFmeditem();
      } else {
        this.queryInfo.pageNum = page;
        this.getFmeditemList();
      }
    },

    //查询所有项目列表
    async getFmeditemList() {
      const { data: res } = await this.$http.get(`fmeditem/queryFmeditemArr`, {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取医生职称信息失败");
      }
      this.fmeditemList = res.list;
      this.total = res.total;
      console.log(res);
    },
    //查询所有费用分类
    async getExpItem() {
      const { data: res } = await this.$http.get(`fmeditem/queryExpItem`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取科室信息失败");
      }
      this.options1 = res.list;
      console.log(res);
    },
    //查询所有执行科室分类
    async getDeptItem() {
      const { data: res } = await this.$http.get(`fmeditem/queryDeptItem`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取科室信息失败");
      }
      this.options2 = res.list;
      console.log(res);
    },
    //根据条件查询科室信息
    async queryFmeditem() {
      const { data: res } = await this.$http.post(
        "fmeditem/queryFmeditem",
        this.queryForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取信息失败");
      }
      this.fmeditemList = res.list;
      this.total = res.total;
      this.$refs.searchFormRef.resetFields();
      console.log(res);
    },

    //添加项目信息
    async sureAdd() {
    this.$refs.itemFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

      const { data: res } = await this.$http.post(
        `fmeditem/insertFmeditem`,
        this.itemForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("添加项目信息失败");
        console.log(res.meta.status);
      }
      this.$refs.itemFormRef.resetFields();
      this.itemDialogVisible = false;
      this.getFmeditemList();
      })
    },

    //修改对话框数据回显
    async showEditDialog(row) {
      this.updateDialogVisible = true;
      //根据id获取用户信息
      const { data: res } = await this.$http.get(
        `fmeditem/selectFmeditemById`,
        { params: { id: row } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("根据id用户信息失败");
      }
      console.log(res);
      this.updateForm.itemcode = String(res.item.itemcode);
      this.updateForm.itemname = String(res.item.itemname);
      this.updateForm.format = String(res.item.format);
      this.updateForm.mnemoniccode = String(res.item.mnemoniccode);
      this.updateForm.price = parseFloat(res.item.price).toFixed(2);
      this.updateForm.expclassid = res.item.expclassid;
      this.updateForm.deptid = res.item.deptid;
      this.updateForm.recordtype = res.item.recordtype;
      this.updateForm.id = String(row);
    },

    //确定修改项目信息
    async sureUpdate() {
     this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

      const { data: res } = await this.$http.post(
        `fmeditem/updateFmed`,
        this.updateForm
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改项目信息失败");
      }
      this.$refs.updateFormRef.resetFields();
      this.getFmeditemList();
      this.updateDialogVisible = false;
     })
    },
    //根据id删除科室信息
    async removeFmedById(row) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.get(`fmeditem/deleteFmedById`, {
        params: { id: row },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("删除项目信息失败");
      }
      this.getFmeditemList();
    },
    //批量删除
    async removeBatch(rows) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      var ids = [];
      rows.forEach((element) => {
        ids.push(element.id);
      });
      //发送删除请求
      const { data: res } = await this.$http.post(`fmeditem/deleteByChoose`, {
        info: ids,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户信息失败");
      }
      this.getFmeditemList();
    },

    //批量删除 将复选框选中id放进数组
    selsChange(sels) {
      this.sels = sels;
    },

    uploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.meta.status == 200) {
        this.$message({
          message: "批量添加成功！",
          type: "success",
        });
        this.$refs.upload.clearFiles();
        this.getFmeditemList();
        
      } else {
        this.$message({
          message: "批量添加失败！",
          type: "error",
        });
      }
    },
    uploadFalse(response, file, fileList) {
      this.$message({
        message: "文件上传失败！",
        type: "error",
      });
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message({
          message: "上传模板只能是 xls、xlsx格式!",
          type: "error",
        });
      }
      if (!isLt2M) {
        console.log("上传模板大小不能超过 10MB!");
        this.$message({
          message: "上传模板大小不能超过 10MB!",
          type: "error",
        });
      }
      return extension || extension2 || extension3 || (extension4 && isLt2M);
    },
    uploadUrl: function () {
      return "http://localhost:8085/his/fmeditem/ExcelInsertFmed";
      
    },

    downloadDemo() {
      let url = "/fmeditem/downloadExcel";
      let thistime = new Date();
      let suftime = thistime.getTime();
      this.exportData(url, null, "数据模板_" + suftime);
    },

    exportData(url, data, fileName) {
      this.$http({
        method: "POST",
        url: url,
        data: data,
        responseType: "blob",
      })
        .then((response) => {
          if (!response) {
            return;
          }
          const blob = new Blob([response.data]);
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            let u = window.URL.createObjectURL(response.data);
            let aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = u;
            aLink.setAttribute("download", fileName + ".xlsx");
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
            window.URL.revokeObjectURL(u);
          }
        })
        .catch((error) => {
          throw error;
        });
    },
  },
};
</script>
<style lang="less" scoped>
</style>